<template>
    <div class="login-container">
        <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="right"
            size="mini"
        >
            <div class="title-container">
                <h3 class="title">后台管理登录</h3>
            </div>

            <el-form-item prop="accounttype">
                <span class="svg-container">
                    <svg-icon icon-class="authRole" />
                </span>
                <el-select
                    v-model="loginForm.authorizeType"
                    placeholder="请选择登录方式"
                    style="margin: 0px"
                    @change="setRules"
                >
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        style="width: 100%"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <!-- 短信验证登录 -->
            <template v-if="loginForm.authorizeType == 'M'">
                <el-form-item prop="telephone">
                    <span class="svg-container">
                        <svg-icon icon-class="user" />
                    </span>
                    <el-input
                        ref="telephone"
                        v-model="loginForm.telephone"
                        placeholder="请输入手机号"
                        name="telephone"
                        type="text"
                        tabindex="1"
                        autocomplete="on"
                        :maxlength="64"
                        @keyup.enter.native="handleLogin"
                    />
                </el-form-item>

                <el-form-item prop="captcha" class="captcha">
                    <span class="svg-container">
                        <svg-icon icon-class="captcha" />
                    </span>
                    <el-input
                        ref="captcha"
                        v-model="loginForm.captcha"
                        placeholder="验证码"
                        name="captcha"
                        type="text"
                        tabindex="3"
                        :maxlength="4"
                        @keyup.enter.native="handleLogin"
                    />
                    <img :src="captcha.base64Img" @click="genCaptcha" />
                </el-form-item>

                <el-form-item prop="phoneCaptcha">
                    <span class="svg-container">
                        <svg-icon icon-class="password" />
                    </span>
                    <el-input
                        ref="phoneCaptcha"
                        v-model="loginForm.phoneCaptcha"
                        type="text"
                        placeholder="请输入短信验证码"
                        name="phoneCaptcha"
                        tabindex="2"
                        autocomplete="on"
                        :maxlength="64"
                        style="width: 64%"
                        @keyup.enter.native="handleLogin"
                    />
                    <el-button
                        id="phonebtn"
                        type="primary"
                        style="width: 101px"
                        :disabled="disableBtn"
                        @click="settime()"
                        >{{ btnText }}</el-button
                    >
                </el-form-item>
            </template>
            <!-- 其他 -->
            <template v-else>
                <!-- 用户登录 -->
                <template v-if="loginForm.authorizeType == 'U'">
                    <el-form-item prop="username">
                        <span class="svg-container">
                            <svg-icon icon-class="user" />
                        </span>
                        <el-input
                            ref="username"
                            v-model="loginForm.username"
                            placeholder="账号"
                            name="username"
                            type="text"
                            tabindex="1"
                            autocomplete="on"
                            :maxlength="64"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>

                    <el-form-item prop="password">
                        <span class="svg-container">
                            <svg-icon icon-class="password" />
                        </span>
                        <el-input
                            ref="password"
                            v-model="loginForm.password"
                            type="password"
                            placeholder="密码"
                            name="password"
                            tabindex="2"
                            autocomplete="on"
                            :maxlength="64"
                            :show-password="true"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>

                    <el-form-item prop="telephone">
                        <span class="svg-container">
                            <svg-icon icon-class="phone-fill" />
                        </span>
                        <el-input
                            ref="telephone"
                            v-model="loginForm.telephone"
                            placeholder="请输入手机号"
                            name="telephone"
                            type="text"
                            tabindex="3"
                            autocomplete="on"
                            :maxlength="64"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>

                    <el-form-item prop="captcha" class="captcha">
                        <span class="svg-container">
                            <svg-icon icon-class="captcha" />
                        </span>
                        <el-input
                            ref="captcha"
                            v-model="loginForm.captcha"
                            placeholder="验证码"
                            name="captcha"
                            type="text"
                            tabindex="4"
                            :maxlength="4"
                            @keyup.enter.native="handleLogin"
                        />
                        <img :src="captcha.base64Img" @click="genCaptcha" />
                    </el-form-item>

                    <el-form-item prop="phoneCaptcha">
                        <span class="svg-container">
                            <svg-icon icon-class="smsCaptcha" />
                        </span>
                        <el-input
                            ref="phoneCaptcha"
                            v-model="loginForm.phoneCaptcha"
                            type="text"
                            placeholder="请输入短信验证码"
                            name="phoneCaptcha"
                            tabindex="5"
                            autocomplete="on"
                            :maxlength="6"
                            style="width: 64%"
                            @keyup.enter.native="handleLogin"
                        />
                        <el-button
                            id="phonebtn"
                            type="primary"
                            style="width: 101px"
                            :disabled="disableBtn"
                            @click="querySmsCaptcha()"
                            >{{ btnText }}</el-button
                        >
                    </el-form-item>
                </template>
                <!-- 人力资源Id登录 -->
                <template v-if="loginForm.authorizeType == 'H'">
                    <el-form-item prop="HrId">
                        <span class="svg-container">
                            <svg-icon icon-class="user" />
                        </span>
                        <el-input
                            ref="HrId"
                            v-model="loginForm.HrId"
                            placeholder="请输入人力资源Id"
                            name="HrId"
                            type="text"
                            tabindex="1"
                            autocomplete="on"
                            :maxlength="64"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>

                    <el-form-item prop="password">
                        <span class="svg-container">
                            <svg-icon icon-class="password" />
                        </span>
                        <el-input
                            ref="password"
                            v-model="loginForm.password"
                            type="password"
                            placeholder="密码"
                            name="password"
                            tabindex="2"
                            autocomplete="on"
                            :maxlength="64"
                            :show-password="true"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>
                </template>
                <!-- NoteId登录 -->
                <template v-if="loginForm.authorizeType == 'N'">
                    <el-form-item prop="NoteId">
                        <span class="svg-container">
                            <svg-icon icon-class="user" />
                        </span>
                        <el-input
                            ref="NoteId"
                            v-model="loginForm.NoteId"
                            placeholder="请输入NoteId"
                            name="NoteId"
                            type="text"
                            tabindex="1"
                            autocomplete="on"
                            :maxlength="64"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>

                    <el-form-item prop="password">
                        <span class="svg-container">
                            <svg-icon icon-class="password" />
                        </span>
                        <el-input
                            ref="password"
                            v-model="loginForm.password"
                            type="password"
                            placeholder="密码"
                            name="password"
                            tabindex="2"
                            autocomplete="on"
                            :maxlength="64"
                            :show-password="true"
                            @keyup.enter.native="handleLogin"
                        />
                    </el-form-item>
                </template>
            </template>

            <el-button
                :loading="loading"
                type="primary"
                style="width: 100%; margin-bottom: 30px"
                size="small"
                @click.native.prevent="handleLogin"
            >
                登录
            </el-button>
        </el-form>
    </div>
</template>

<script>
    import md5 from "js-md5";
    import { getCaptchaw150h40, getSmsCaptcha } from "@/api/base/common";
    import { encryptSM2, decryptSM4, encryptSM4 } from "@/utils/sm-crypto.js";

    export default {
        name: "Login",
        data() {
            const validateUsername = (rule, value, callback) => {
                callback();
            };
            const validateHrId = (rule, value, callback) => {
                callback();
            };
            const validateNoteId = (rule, value, callback) => {
                callback();
            };
            const telephone = (rule, value, callback) => {
                setTimeout(() => {
                    if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
                        callback(new Error("请输入正确的号码"));
                        this.pho = false;
                    } else {
                        callback();
                        this.pho = true;
                    }
                    this.disableBtn = !(this.cap && this.pho); // 手机号与验证码正确时才可发送短信验证码
                }, 500);
            };
            const validatePassword = (rule, value, callback) => {
                callback();
            };
            const validateCaptcha = (rule, value, callback) => {
                if (
                    value !== "" &&
                    this.captcha.captchHash !== md5(value.toUpperCase())
                ) {
                    callback(new Error("验证码错误"));
                    this.cap = false;
                } else {
                    callback();
                    this.cap = true;
                }
                this.disableBtn = !this.pho; // 手机号与验证码正确时才可发送短信验证码
            };
            const validatePhoneCaptcha = (rule, value, callback) => {
                callback();
            };
            return {
                captcha: {
                    base64Img: "",
                    captchHash: "",
                    publicKey: "",
                },
                loginForm: {
                    username: "",
                    password: "",
                    HrId: "",
                    NoteId: "",
                    telephone: "",
                    phoneCaptcha: "",
                    captcha: "",
                    captchaId: "",
                    authorizeType: "U",
                },
                submitForm: {
                    username: "",
                    password: "",
                    captcha: "",
                    captchaId: "",
                    authorizeType: "",
                    phone: "",
                    smsCaptcha: "",
                },
                loginRules: {
                    username: [
                        {
                            required: true,
                            message: "请输入账号",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validateUsername },
                    ],
                    HrId: [
                        {
                            required: true,
                            message: "请输入人力ID",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validateHrId },
                    ],
                    NoteId: [
                        {
                            required: true,
                            message: "请输入NoteId  ",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validateNoteId },
                    ],
                    telephone: [
                        {
                            required: true,
                            message: "请输入手机号",
                            trigger: "change",
                        },
                        { trigger: "change", validator: telephone },
                    ],
                    password: [
                        {
                            required: true,
                            message: "请输入登录密码",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validatePassword },
                    ],
                    captcha: [
                        {
                            required: true,
                            message: "请输入验证码",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validateCaptcha },
                    ],
                    phoneCaptcha: [
                        {
                            required: true,
                            message: "请输入短信验证码",
                            trigger: "change",
                        },
                        { trigger: "change", validator: validatePhoneCaptcha },
                    ],
                },
                loading: false,
                showDialog: false,
                redirect: undefined,
                otherQuery: {},
                options: [
                    {
                        value: "U",
                        label: "用户名登录",
                    },
                    // , {
                    //   value: 'H',
                    //   label: '人力ID认证'
                    // }, {
                    //   value: 'N',
                    //   label: 'NotesId认证'
                    // }
                    // {
                    //   value: 'M',
                    //   label: '手机验证码认证'
                    // }
                ],
                // value: 'U',
                countdown: 30, // 发送验证码倒计时
                btnText: "获取验证码",
                disableBtn: true, // 是否可以点击发送验证码按钮
                pho: false, // 手机号是否正确
                cap: false, // 验证码是否正确
            };
        },
        watch: {
            $route: {
                handler: function (route) {
                    const query = route.query;
                    if (query) {
                        this.redirect = query.redirect;
                        this.otherQuery = this.getOtherQuery(query);
                    }
                },
                immediate: true,
            },
        },
        mounted() {
            if (this.loginForm.username === "") {
                this.$refs.username.focus();
            } else if (this.loginForm.password === "") {
                this.$refs.password.focus();
            } else if (this.loginForm.captcha === "") {
                this.$refs.captcha.focus();
            }
            this.genCaptcha();
        },
        methods: {
            setRules() {
                this.$nextTick(() => {
                    this.$refs.loginForm.clearValidate(); // 等弹窗里的form表单的dom渲染完在执行this.$refs.staffForm.resetFields()，去除验证
                    this.genCaptcha(); // 重新获取验证码
                });
            },
            settime() {
                if (this.countdown === 0) {
                    // TODO 短信验证码接口
                    this.disableBtn = false;
                    this.btnText = "获取验证码";
                    this.countdown = 30;
                    return;
                } else {
                    this.disableBtn = true;
                    this.btnText = "重新发送(" + this.countdown + ")";
                    this.countdown--;
                    setTimeout(() => {
                        this.settime();
                    }, 1000);
                }
            },
            querySmsCaptcha() {
                let queryParams = {
                    type: this.loginForm.authorizeType,
                    username: this.loginForm.username,
                    phone: this.loginForm.telephone,
                    captcha: this.loginForm.captcha,
                    captchaId: this.loginForm.captchaId,
                };
                getSmsCaptcha(queryParams).then((response) => {
                    console.log(response);
                    this.settime();
                });
            },
            genCaptcha() {
                getCaptchaw150h40().then(
                    (response) => {
                        this.captcha.captchHash = response.data.hashCode;
                        this.captcha.base64Img =
                            "data:image/gif;base64," + response.data.base64Img;
                        this.captcha.publicKey = response.data.publicKey;
                        this.loginForm.captcha = "";
                        this.loginForm.captchaId = response.data.captchaId;
                    },
                    (response) => {
                        this.captcha.base64Img =
                            "";
                    }
                );
            },
            handleLogin() {
                // TODO 登录验证及接口
                if (this.loginForm.authorizeType === "U") {
                    if (this.loginForm.username === "") {
                        this.$refs.username.focus();
                        return;
                    } else if (this.loginForm.password === "") {
                        this.$refs.password.focus();
                        return;
                    } else if (this.loginForm.telephone === "") {
                        this.$refs.telephone.focus();
                        return;
                    } else if (this.loginForm.captcha === "") {
                        this.$refs.captcha.focus();
                        return;
                    } else if (this.loginForm.phoneCaptcha === "") {
                        this.$refs.phoneCaptcha.focus();
                        return;
                    }
                } else if (this.loginForm.authorizeType === "H") {
                    if (this.loginForm.HrId === "") {
                        this.$refs.HrId.focus();
                        return;
                    } else if (this.loginForm.password === "") {
                        this.$refs.password.focus();
                        return;
                    } else if (this.loginForm.captcha === "") {
                        this.$refs.captcha.focus();
                        return;
                    }
                } else if (this.loginForm.authorizeType === "N") {
                    if (this.loginForm.NoteId === "") {
                        this.$refs.NoteId.focus();
                        return;
                    } else if (this.loginForm.password === "") {
                        this.$refs.password.focus();
                        return;
                    } else if (this.loginForm.captcha === "") {
                        this.$refs.captcha.focus();
                        return;
                    }
                } else if (this.loginForm.authorizeType === "M") {
                    if (this.loginForm.telephone === "") {
                        this.$refs.telephone.focus();
                        return;
                    } else if (this.loginForm.captcha === "") {
                        this.$refs.captcha.focus();
                        return;
                    } else if (this.loginForm.phoneCaptcha === "") {
                        this.$refs.phoneCaptcha.focus();
                        return;
                    }
                }

                this.$refs.loginForm.validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        if (this.loginForm.authorizeType === "U") {
                            this.submitForm.username = this.loginForm.username;
                            this.submitForm.password = this.loginForm.password;
                        } else if (this.loginForm.authorizeType === "H") {
                            this.submitForm.username = this.loginForm.HrId;
                            this.submitForm.password = this.loginForm.password;
                        } else if (this.loginForm.authorizeType === "N") {
                            this.submitForm.username = this.loginForm.NoteId;
                            this.submitForm.password = this.loginForm.password;
                        } else if (this.loginForm.authorizeType === "M") {
                            this.submitForm.username = this.loginForm.telephone;
                            this.submitForm.password = this.loginForm.phoneCaptcha;
                        }
                        this.submitForm.captcha = this.loginForm.captcha;
                        this.submitForm.captchaId = this.loginForm.captchaId;
                        this.submitForm.authorizeType =
                            this.loginForm.authorizeType;
                        // 密码加密
                        this.submitForm.password = encryptSM2(
                            this.submitForm.password,
                            this.captcha.publicKey
                        );
                        this.submitForm.phone = this.loginForm.telephone;
                        this.submitForm.smsCaptcha = this.loginForm.phoneCaptcha;
                        console.log(this.submitForm);
                        this.$store
                            .dispatch("user/login", this.submitForm)
                            .then(
                                () => {
                                    this.$router
                                        .push({
                                            path: this.redirect || "/",
                                            query: this.otherQuery,
                                        })
                                        .catch((e) => {
                                            console.log(e);
                                        });
                                },
                                () => {
                                    // 登陆失败刷新验证码
                                    this.genCaptcha();
                                    this.loading = false;
                                }
                            )
                            .catch(() => {
                                this.loading = false;
                            });
                    } else {
                        return false;
                    }
                });
            },
            getOtherQuery(query) {
                return Object.keys(query).reduce((acc, cur) => {
                    if (cur !== "redirect") {
                        acc[cur] = query[cur];
                    }
                    return acc;
                }, {});
            },
        },
    };
</script>

<style lang="scss">
    $bg: #283443;
    $light_gray: #fff;
    $cursor: #fff;

    @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
        .login-container .el-input input {
            color: $cursor;
        }
    }

    /* reset element-ui css */
    .login-container {
        .el-select,
        .el-input {
            display: inline-block;
            height: 30px;
            width: 85%;

            input {
                background: transparent;
                border: 0px;
                -webkit-appearance: none;
                border-radius: 0px;
                padding: 12px 5px 12px 15px;
                color: $light_gray;
                height: 30px;
                caret-color: $cursor;

                &:-webkit-autofill {
                    box-shadow: 0 0 0px 1000px $bg inset !important;
                    -webkit-text-fill-color: $cursor !important;
                }
            }
        }

        .login-type .el-input__suffix {
            display: none;
        }

        .captcha {
            .el-input {
                width: 55%;
            }

            img {
                border-top-left-radius: 0px;
                border-bottom-left-radius: 0px;
                border-left: 0px;
                float: right;
                background: transparent;
                border: 0px;
                -webkit-appearance: none;
                border-radius: 0px;
                padding: 5px 5px 5px 5px;
                color: #fff;
                height: 40px;
                caret-color: #fff;
            }
        }

        .el-form-item {
            border: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            color: #454545;
        }
    }

    $bg: #2d3a4b;
    $dark_gray: #889aa4;
    $light_gray: #eee;

    .login-container {
        min-height: 100%;
        width: 100%;
        background-color: $bg;
        overflow: hidden;

        .login-form {
            position: relative;
            width: 450px;
            max-width: 100%;
            @media screen and (min-height: 0px) and (max-height: 900px) {
                padding: 100px 35px 0;
            }
            @media screen and (min-height: 901px) {
                padding: 180px 35px 0;
            }
            margin: 0 auto;
            overflow: hidden;
        }

        .tips {
            font-size: 14px;
            color: #fff;
            margin-bottom: 10px;

            span {
                &:first-of-type {
                    margin-right: 16px;
                }
            }
        }

        .svg-container {
            padding: 6px 5px 6px 15px;
            color: $dark_gray;
            vertical-align: middle;
            width: 30px;
            display: inline-block;
        }

        .title-container {
            position: relative;

            .title {
                font-size: 26px;
                color: $light_gray;
                margin: 0px auto 40px auto;
                text-align: center;
                font-weight: bold;
            }

            .set-language {
                color: #fff;
                position: absolute;
                top: 3px;
                font-size: 18px;
                right: 0px;
                cursor: pointer;
            }
        }
    }

    /deep/.el-input {
        margin: 0px;
        width: 100%;
    }
    /deep/.el-input--mini {
        margin: 0px;
    }
    /deep/.el-input--suffix {
        margin: 0px;
    }
</style>
